package com.qyer.log;

import static com.qyer.search.Constants.SEPARATOR2;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.qyer.search.model.SearchParameter;
import com.qyer.search.model.SearchParameterOrigin;
import com.qyer.search.model.User;
import com.qyer.search.model.lastminute.SKU;
import com.qyer.search.model.result.SearchPackage;
import com.qyer.search.report.SearchReportItem;
import com.qyer.search.utils.JsonOperator;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * User: Z J Wu Date: 2015/08/20 Time: 00:00 Package: com.qyer.log
 */
public class ContentShowLogger {

  private static final Logger LOGGER = LoggerFactory.getLogger(ContentShowLogger.class);

  public static void logSearchResult(SearchReportItem sri) throws JsonProcessingException {
    if (sri == null) {
      return;
    }
    StringBuilder sb = new StringBuilder();
    SearchParameterOrigin searchParameter = sri.getSearchParameter();
    User user = searchParameter.getUser();

    sb.append(searchParameter.getRequestId());
    sb.append(SEPARATOR2);
    sb.append(searchParameter.getContext());
    sb.append(SEPARATOR2);
    sb.append(user.getUid());
    sb.append(SEPARATOR2);
    sb.append(user.getUniqueId());
    sb.append(SEPARATOR2);
    sb.append(JsonOperator.getInstance().toJson(searchParameter));
    sb.append(SEPARATOR2);

    List<? extends SearchPackage> searchPackages = sri.getResultPackages();
    if (CollectionUtils.isNotEmpty(searchPackages)) {
      Map<Integer, List<Integer>> resultIds = new HashMap<>(searchPackages.size());
      List<Integer> ids;
      List<SKU> skus;
      int type1 = 0;
      for (SearchPackage searchPackage : searchPackages) {
        skus = searchPackage.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
          continue;
        }
        ids = new ArrayList<>(skus.size());
        for (SKU sku : skus) {
          type1 = sku.getType1();
          ids.add(sku.getId());
        }
        resultIds.put(type1, ids);
      }
      sb.append(JsonOperator.getInstance().toJson(resultIds));
    }
    LOGGER.info(sb.toString());
  }
}
